// 发布订阅类
import EventTypes from '@/config/EventTypeConfig'

interface EventFace {
    on: (key: string, func: Function) => void,
    off: (key: string, func: Function) => void,
    emit: (key: string, ...args: Array<any>) => void
}

interface List {
    [key: string]: Array<Function>
}

export default class EventManager implements EventFace {
    list: List

    constructor() {
        this.list = {}
    }

    on(key: string, func: Function) {
        if (EventTypes[key] == undefined) return console.log(`${key} 事件类型未定义`)
        if (!this.list[key]) this.list[key] = []
        this.list[key].push(func)
    }

    off(key: string, func: Function) {
        if (!this.list[key]) return false
        if (!func) {
            this.list && (this.list[key].length = 0)
            return this
        }
        let index = this.list[key].findIndex((item: Function) => item === func)
        this.list[key].splice(index, 1)
        return this
    }

    emit(key: string, ...args: Array<any>) {
        if (EventTypes[key] == undefined) return console.log(`${key} 事件类型未定义，无法触发`)
        let funcs = this.list[key]
        if (!funcs) return false
        funcs.forEach((func: any) => {
            func.apply(this, args)
        })
        return this
    }
}